package com.example.zy.car.view.camera;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.example.zy.car.R;
import com.example.zy.car.config.Constant;
import com.example.zy.car.utils.NormalUtils;
import com.example.zy.car.view.tag.TagInfo;
import com.example.zy.car.view.tag.TagView;
import com.example.zy.car.view.tag.TagViewLeft;
import com.example.zy.car.view.tag.TagViewRight;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


/**
 * Created by zy on 2016/4/12.
 */
public class AddTagActivity extends Activity implements View.OnClickListener, TagView.TagViewListener {

    private String TAG = "AddTagActivity";
    private final static int TEXTSIZE = 12;        //Tagview的字体大小

    private RelativeLayout mImageRootLayout;
    private LinearLayout mTagLinearLayout;
    private ImageView mImageView;
    private ImageView mTagNormal;
    private ImageView mTagGeo;
    private ImageView mTagUser;


    private Uri mImageUri;            //目标图片的Uri
    private String mImagePath;        //目标图片的路径

    private Boolean isTagLayShow = false;    //标签图标区域是否显示

    private float mPointX = 0;
    private float mPointY = 0;
    private float x1;
    private float y1;

    private List<TagView> tagViews = new ArrayList<TagView>();
    private List<TagInfo> tagInfoList = new ArrayList<TagInfo>();
    private int screenWidth;
    private int screenHeight;

    private final Handler mHandler = new Handler();

    /**
     * 记录当前手指位置在屏幕上的横坐标值
     */
    private float xInScreen;

    /**
     * 记录当前手指位置在屏幕上的纵坐标值
     */
    private float yInScreen;

    /**
     * 记录手指按下时在屏幕上的横坐标的值
     */
    private float xDownInScreen;

    /**
     * 记录手指按下时在屏幕上的纵坐标的值
     */
    private float yDownInScreen;

    /**
     * 记录系统状态栏的高度
     */
    private static int statusBarHeight;

    /**
     * 记录手指按下时在小悬浮窗的View上的横坐标的值
     */
    private float xInView;

    /**
     * 记录手指按下时在小悬浮窗的View上的纵坐标的值
     */
    private float yInView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_tag);

//        mImagePath = getIntent().getStringExtra(TakePicActivity.CROP_IMAGE_URI);
//        mImageUri = Uri.parse(mImagePath);
        screenWidth=getWindowManager().getDefaultDisplay().getWidth();
        screenHeight=getWindowManager().getDefaultDisplay().getHeight();
        initView();

    }

    private void initView() {
        mImageView = (ImageView) findViewById(R.id.at_image);
        mImageView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                        mPointX = event.getX();
                        mPointY = event.getY();
                        Log.d(TAG,"----------------->"+String.valueOf(mPointX));
                        Log.d(TAG,"----------------->"+String.valueOf(mPointY));
//                        showTagLinearLayout(mPointX, mPointY);
                        editTagInfo(1);
                        break;
                }

                return true;
            }
        });

        mImageRootLayout = (RelativeLayout) findViewById(R.id.at_image_layout);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT );
        mImageView.setLayoutParams(params);
//        if (mImageUri != null) {
        mImageView.setImageResource(R.drawable.item02);
//        }

//        mTagLinearLayout = (LinearLayout) findViewById(R.id.at_tag_layout);
//        RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//        mTagLinearLayout.setLayoutParams(params2);

//        mTagNormal = (ImageView) findViewById(R.id.at_tag_image1);
//        mTagGeo = (ImageView) findViewById(R.id.at_tag_image2);
//        mTagUser = (ImageView) findViewById(R.id.at_tag_image3);
//        mTagNormal.setOnClickListener(this);
//        mTagGeo.setOnClickListener(this);
//        mTagUser.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.at_show:
//
//                JSONArray tagInfoArray = new JSONArray();
//                for (TagInfo info : tagInfoList) {
//                    JSONObject infoJson = info.getjson();
//                    tagInfoArray.put(infoJson);
//                }
//                Intent intent = new Intent(this, ShowTagActivity.class);
//                intent.putExtra(TakePicActivity.CROP_IMAGE_URI, mImagePath);
//                intent.putExtra("tagInfoList", tagInfoArray.toString());
//                startActivity(intent);
//
//                break;
//            case R.id.at_finish:
//                saveImageAndFinish();
//
//                break;
//            case R.id.at_tag_image1:
//
//                break;
//            case R.id.at_tag_image2:
//                editTagInfo(2);
//                break;
//            case R.id.at_tag_image3:
//                editTagInfo(3);
//                break;
            default:
                break;
        }
    }
    /**
     * 编辑标签信息
     */
    private void editTagInfo(int k) {
        //标签图标区域消失
//        showTagLinearLayout(0, 0);
        Log.d(TAG,"---------------------------->"+k);

        TagInfo tagInfo = new TagInfo();
        tagInfo.bid = 2L;
        tagInfo.bname = "Hello PMMQ " + k;
        tagInfo.direct = getDirection(tagInfo.bname);
        tagInfo.pic_x = mPointX / screenWidth;
        tagInfo.pic_y = mPointY / screenHeight;
        tagInfo.type = getRandomType();
        switch (tagInfo.direct) {
            case Left:
                tagInfo.leftMargin = (int) (mPointX - 15 * Constant.scale);    //根据屏幕密度计算使动画中心在点击点，15dp是margin
                tagInfo.topMargin = (int) (mPointY - 15 * Constant.scale);
                tagInfo.rightMargin = 0;
                tagInfo.bottomMargin = 0;
                break;
            case Right:
                tagInfo.leftMargin = 0;
                tagInfo.topMargin = (int) (mPointY - 15 * Constant.scale);
                tagInfo.rightMargin = screenWidth- (int) mPointX - (int) (15 * Constant.scale);
                tagInfo.bottomMargin = 0;
                break;
        }
        Log.d(TAG,"-------------------------->"+tagInfo.pic_x);
        Log.d(TAG,"-------------------------->"+tagInfo.pic_y);
        addTagInfo(tagInfo);
        Log.d(TAG,"-------------------------->"+tagInfo.topMargin);
        Log.d(TAG,"-------------------------->"+tagInfo.leftMargin);
        Log.d(TAG,"-------------------------->"+tagInfo.rightMargin);
        Log.d(TAG,"-------------------------->"+tagInfo.bottomMargin);
    }

    /**
     * 添加标签
     */
    private void addTagInfo(final TagInfo tagInfo) {
        TagView tagView = null;
        switch (tagInfo.direct) {
            case Left:
                tagView = new TagViewLeft(this, null);
                break;
            case Right:
                tagView = new TagViewRight(this, null);
                break;
        }
        tagView.setData(tagInfo);
        tagView.setTagViewListener(this);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(tagInfo.leftMargin, tagInfo.topMargin, tagInfo.rightMargin, tagInfo.bottomMargin);
        mImageRootLayout.addView(tagView, params);
        //添加TagView的滑动事件
        tagView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        // 手指按下时记录必要数据,纵坐标的值都需要减去状态栏高度
                        xInView = event.getX();
                        yInView = event.getY();
                        xDownInScreen = event.getRawX();
                        yDownInScreen = event.getRawY() - getStatusBarHeight();
                        xInScreen = event.getRawX();
                        yInScreen = event.getRawY() - getStatusBarHeight();
                        x1 = event.getRawX();
                        y1 = event.getRawY() - getStatusBarHeight();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        xInScreen = event.getRawX();
                        yInScreen = event.getRawY() - getStatusBarHeight();
                        //手指超出边界时，使y值等于边界值，此处view等于屏幕宽度，所以不考虑x值
                        if ((yInScreen - yInView) < 0) {
                            yInScreen = yInView;
                            Log.d(TAG,"-------------------------->"+yInScreen);
                        } else if ((yInScreen + v.getHeight() - yInView) > screenHeight) {
                            yInScreen = screenHeight - v.getHeight() + yInView;
                            Log.d(TAG,"-------------------------->"+yInScreen);
                        }
                        //当要移动tagview的时候，每次进行界面的位置刷新操作
                        updateTagViewPosition(v, tagInfo);
                        xDownInScreen = xInScreen;
                        yDownInScreen = yInScreen;

                        break;
                    case MotionEvent.ACTION_UP:
                        switch (tagInfo.direct) {
                            case Left:
                                tagInfo.pic_x = (v.getLeft() + 15 * Constant.scale) / screenWidth;
                                tagInfo.pic_y = (v.getTop() + 15 * Constant.scale) / screenHeight;
                                break;
                            case Right:
                                tagInfo.pic_x = (v.getRight() - 15 * Constant.scale) /screenWidth;
                                tagInfo.pic_y = (v.getTop() + 15 * Constant.scale) / screenHeight;
                                break;
                        }
                        Log.d(TAG,"-------------------------->"+"滑动结束的"+tagInfo.pic_x);
                        Log.d(TAG,"-------------------------->"+"滑动结束的"+tagInfo.pic_y);
                        if (Math.abs(x1 - xInScreen) < 5 && Math.abs(y1 - yInScreen) < 5) {
                            return false;
                        } else {
                            return true;
                        }
                }

                return false;
            }
        });
        tagInfoList.add(tagInfo);
        tagViews.add(tagView);
    }

    /**
     * 移动TagView，更新位置
     */
    private void updateTagViewPosition(View v, TagInfo tagInfo) {
        //计算位移
        float xMove = xInScreen - xDownInScreen;
        float yMove = yInScreen - yDownInScreen;

        //获取View的宽度，为什么不用v.getWidth();?因为Right方向的布局有问题，是从屏幕左边缘开始，不符合需求
        int viewWidth = (int) getTagViewWidth(tagInfo.bname);

        switch (tagInfo.direct) {
            case Left:
                tagInfo.leftMargin += xMove;
                tagInfo.topMargin += yMove;
                Log.d(TAG,"-------------------------->"+"1111"+tagInfo.leftMargin);
                //left情况下的边界计算
                if (tagInfo.leftMargin < 0) {
                    tagInfo.leftMargin = 0;
                    Log.d(TAG,"-------------------------->"+"2222"+tagInfo.leftMargin);
                } else if ((tagInfo.leftMargin + viewWidth) > screenWidth) {
                    tagInfo.leftMargin = screenWidth - viewWidth;
                    Log.d(TAG,"-------------------------->"+"3333"+tagInfo.leftMargin);
                }
                break;
            case Right:
                tagInfo.topMargin += yMove;
                tagInfo.rightMargin -= xMove;
                //right情况下的边界计算
                if (tagInfo.rightMargin < 0) {
                    tagInfo.rightMargin = 0;
                } else if ((tagInfo.rightMargin + viewWidth) > screenHeight) {
                    tagInfo.rightMargin = screenHeight - viewWidth;
                }
                break;
        }
        //上下边界计算
        if (tagInfo.topMargin < 0) {
            tagInfo.topMargin = 0;
            Log.d(TAG,"-------------------------->"+"1111"+tagInfo.topMargin);
        } else if ((tagInfo.topMargin + v.getHeight()) > screenHeight) {
            tagInfo.topMargin =screenHeight - v.getHeight();
            Log.d(TAG,"-------------------------->"+"2222"+tagInfo.leftMargin);
        }
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(tagInfo.leftMargin, tagInfo.topMargin, tagInfo.rightMargin, tagInfo.bottomMargin);
        v.setLayoutParams(params);
    }

    /*
     * TagView的点击时相应的事件
     * 
     */
    @Override
    public void onTagViewClicked(final View view, final TagInfo info) {
        new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.at_want_delete)).setPositiveButton(getResources().getString(R.string.at_ok),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int whichButton) {
                        mImageRootLayout.removeView(view);
                        tagViews.remove(view);
                        tagInfoList.remove(info);
//                        Logger.w(TAG, "----> tagViews.size():" + tagViews.size());
//                        Logger.w(TAG, "tagInfoList.size():" + tagInfoList.size());
                    }
                }).setNegativeButton(getResources().getString(R.string.at_cancel), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int whichButton) {
            }
        }).show();
    }

    /**
     * 获取TagView的宽度
     */
    private float getTagViewWidth(String str) {
        float viewWidth = NormalUtils.GetTextWidth(str, TEXTSIZE * Constant.scale);
        Log.d(TAG,"---------------------->"+"1111111"+viewWidth);
        //46dp是TagView除去text部分的宽度，可以从布局中查看
        viewWidth += (46 * Constant.scale);
        Log.d(TAG,"---------------------->"+"2222222"+viewWidth);
        return viewWidth;
    }
    /**
     * 获取TagView的方向
     */
    private TagInfo.Direction getDirection(String str) {
        float showSize = NormalUtils.GetTextWidth(str, TEXTSIZE * Constant.scale);
        showSize += (32 * Constant.scale);
        System.out.println("------------->getDirection showSize:" + showSize);
        System.out.println(mPointX+"------------>");
        if ((mPointX + showSize) >(screenWidth/2) ) {
            return TagInfo.Direction.Right;
        } else {
            return TagInfo.Direction.Left;
        }
    }

    private TagInfo.Type getRandomType() {
        Random random = new Random();
        int ran = random.nextInt(TagInfo.Type.size());
        if (0 == ran) {
            return TagInfo.Type.Undefined;
        } else if (1 == ran) {
            return TagInfo.Type.Exists;
        } else if (2 == ran) {
            return TagInfo.Type.CustomPoint;
        } else {
            return TagInfo.Type.OfficalPoint;
        }
    }

    /**
     * 显示与隐藏标签图标区域
     */
//    private void showTagLinearLayout(float x, float y) {
//        if (isTagLayShow) {
//            mImageView.setImageResource(R.drawable.item02);
//            mTagLinearLayout.setVisibility(View.GONE);
//            isTagLayShow = false;
//            //设置TagView的可以移动
//            setTagViewEnable(true);
//        } else {
////            addPoint(x, y);
//            mTagLinearLayout.setVisibility(View.VISIBLE);
//            TranslateAnimation anim = new TranslateAnimation(0, 0, -(Constant.displayWidth / 2), 0);
//            anim.setInterpolator(new BounceInterpolator());
//            anim.setDuration(1000);
//            mTagNormal.setAnimation(anim);
//            mTagGeo.setAnimation(anim);
//            mTagUser.setAnimation(anim);
//            anim.startNow();
//            isTagLayShow = true;
//            //取消TagView的移动
//            setTagViewEnable(false);
//        }
//    }

    /**
     * 设置TagView是否可以点击
     *
     * @param enabled
     */
    private void setTagViewEnable(Boolean enabled) {
        for (TagView view : tagViews) {
            view.setEnabled(enabled);
        }
    }

    /**
     * 用于获取状态栏的高度。
     * @return 返回状态栏高度的像素值。
     */
    private int getStatusBarHeight() {
        if (statusBarHeight == 0) {
            try {
                Class<?> c = Class.forName("com.android.internal.R$dimen");
                Object o = c.newInstance();
                Field field = c.getField("status_bar_height");
                int x = (Integer) field.get(o);
                statusBarHeight = getResources().getDimensionPixelSize(x);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return statusBarHeight;
    }

}

